<template>
	<view class="add-address-page">
		<!-- 顶部导航栏 -->
		<view class="top-nav">
			<view class="nav-back" @click="goBack">
				<text class="back-icon">‹</text>
			</view>
			<text class="nav-title">{{ isEdit ? '编辑地址' : '添加地址' }}</text>
			<view class="nav-placeholder"></view>
		</view>
		
		<!-- 表单内容 -->
		<view class="form-content">
			<view class="form-item">
				<text class="form-label">收货人</text>
				<input 
					class="form-input" 
					v-model="formData.receiverName" 
					placeholder="请输入收货人姓名"
					maxlength="20"
				/>
			</view>
			<view class="form-item">
				<text class="form-label">手机号</text>
				<input 
					class="form-input" 
					v-model="formData.receiverPhone" 
					placeholder="请输入手机号"
					type="number"
					maxlength="11"
				/>
			</view>
			<view class="form-item">
				<text class="form-label">所在地区</text>
				<picker 
					mode="region" 
					:value="regionValue" 
					@change="onRegionChange"
					class="region-picker"
				>
					<view class="picker-view">
						<text class="picker-text" :class="{placeholder: !regionValue[0]}">
							{{ regionValue[0] ? `${regionValue[0]} ${regionValue[1]} ${regionValue[2]}` : '请选择省市区' }}
						</text>
						<text class="picker-arrow">›</text>
					</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label">详细地址</text>
				<textarea 
					class="form-textarea" 
					v-model="formData.detailAddress" 
					placeholder="请输入街道、门牌号等详细地址"
					maxlength="100"
					auto-height
				/>
			</view>
			<view class="form-item checkbox-item">
				<view class="checkbox-wrapper" @click="toggleDefault">
					<view class="checkbox" :class="{checked: formData.isDefault}">
						<text class="checkbox-icon" v-if="formData.isDefault">✓</text>
					</view>
					<text class="checkbox-label">设为默认地址</text>
				</view>
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-bar">
			<view class="save-btn" @click="saveAddress">保存</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false, // 是否为编辑模式
				editIndex: -1, // 编辑的地址索引
				regionValue: ['', '', ''], // 省市区选择值
				formData: {
					receiverName: '',
					receiverPhone: '',
					province: '',
					city: '',
					district: '',
					detailAddress: '',
					isDefault: false
				}
			}
		},
		onLoad(options) {
			// 判断是添加还是编辑
			if (options.action === 'edit') {
				this.isEdit = true;
				this.editIndex = parseInt(options.index) || -1;
				// 解析地址数据
				if (options.addressData) {
					try {
						const addressData = JSON.parse(decodeURIComponent(options.addressData));
						this.formData = {
							receiverName: addressData.receiverName || '',
							receiverPhone: addressData.receiverPhone || '',
							province: addressData.province || '',
							city: addressData.city || '',
							district: addressData.district || '',
							detailAddress: addressData.detailAddress || '',
							isDefault: addressData.isDefault || false
						};
						// 设置地区选择器值
						this.regionValue = [
							addressData.province || '',
							addressData.city || '',
							addressData.district || ''
						];
					} catch (e) {
						console.error('解析地址数据失败', e);
					}
				}
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			// 地区选择改变
			onRegionChange(e) {
				this.regionValue = e.detail.value;
				this.formData.province = e.detail.value[0] || '';
				this.formData.city = e.detail.value[1] || '';
				this.formData.district = e.detail.value[2] || '';
			},
			// 切换默认地址
			toggleDefault() {
				this.formData.isDefault = !this.formData.isDefault;
			},
			// 验证表单
			validateForm() {
				if (!this.formData.receiverName || this.formData.receiverName.trim() === '') {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					});
					return false;
				}
				if (!this.formData.receiverPhone || this.formData.receiverPhone.trim() === '') {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return false;
				}
				// 验证手机号格式
				const phoneReg = /^1[3-9]\d{9}$/;
				if (!phoneReg.test(this.formData.receiverPhone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return false;
				}
				if (!this.formData.province || !this.formData.city || !this.formData.district) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					});
					return false;
				}
				if (!this.formData.detailAddress || this.formData.detailAddress.trim() === '') {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			// 保存地址
			saveAddress() {
				// 验证表单
				if (!this.validateForm()) {
					return;
				}
				
				// 获取地址列表
				let addressList = uni.getStorageSync('addressList') || [];
				
				// 如果设为默认地址，先取消其他地址的默认状态
				if (this.formData.isDefault) {
					addressList.forEach(addr => {
						addr.isDefault = false;
					});
				}
				
				// 构建地址对象
				const addressItem = {
					id: this.isEdit && this.editIndex >= 0 
						? addressList[this.editIndex].id 
						: Date.now(), // 新地址使用时间戳作为ID
					receiverName: this.formData.receiverName.trim(),
					receiverPhone: this.formData.receiverPhone.trim(),
					province: this.formData.province,
					city: this.formData.city,
					district: this.formData.district,
					detailAddress: this.formData.detailAddress.trim(),
					isDefault: this.formData.isDefault
				};
				
				if (this.isEdit && this.editIndex >= 0) {
					// 编辑模式：更新地址
					addressList[this.editIndex] = addressItem;
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
				} else {
					// 添加模式：新增地址
					// 如果这是第一个地址，自动设为默认
					if (addressList.length === 0) {
						addressItem.isDefault = true;
					}
					addressList.push(addressItem);
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
				}
				
				// 保存到本地存储
				uni.setStorageSync('addressList', addressList);
				
				// 延迟返回上一页，让用户看到成功提示
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		}
	}
</script>

<style scoped>
	.add-address-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	/* 顶部导航栏 */
	.top-nav {
		background-color: #2a6df6;
		background-image: url('/static/图层 1@3x.png');
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
		color: #fff;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: relative;
		padding: 0 30rpx;
		box-sizing: border-box;
	}

	.nav-back {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		color: #fff;
		font-size: 48rpx;
		font-weight: 300;
		line-height: 1;
	}

	.nav-title {
		font-size: 18px;
		font-weight: bold;
		flex: 1;
		text-align: center;
	}

	.nav-placeholder {
		width: 60rpx;
	}

	/* 表单内容 */
	.form-content {
		padding: 20rpx;
	}

	.form-item {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		width: 160rpx;
		flex-shrink: 0;
		font-weight: 500;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.form-textarea {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		min-height: 120rpx;
		line-height: 1.6;
	}

	.region-picker {
		flex: 1;
	}

	.picker-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	.picker-text.placeholder {
		color: #999;
	}

	.picker-arrow {
		font-size: 32rpx;
		color: #ccc;
		margin-left: 20rpx;
	}

	.checkbox-item {
		justify-content: space-between;
	}

	.checkbox-wrapper {
		display: flex;
		align-items: center;
		gap: 20rpx;
		flex: 1;
	}

	.checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #ddd;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
	}

	.checkbox.checked {
		background-color: #2a6df6;
		border-color: #2a6df6;
	}

	.checkbox-icon {
		color: #fff;
		font-size: 24rpx;
		line-height: 1;
	}

	.checkbox-label {
		font-size: 28rpx;
		color: #333;
	}

	/* 保存按钮栏 */
	.save-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
		z-index: 10;
	}

	.save-btn {
		width: 100%;
		background-color: #2a6df6;
		color: #fff;
		text-align: center;
		padding: 24rpx 0;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: 500;
	}
</style>
